<template>
  <div class="treeTable-container" v-loading="loading">
    <div class="radioGroup-container" v-if="type == 3">
      是否展示已编制任务清单:
      <a-radio-group v-model="ifShowExist" @change="changeShowExist()">
        <a-radio :value="1"> 是 </a-radio>
        <a-radio :value="2"> 否 </a-radio>
      </a-radio-group>
    </div>
    <!-- table -->
    <vxe-table
      resizable
      class="scrollbarStyle"
      :column-config="{ resizable: true }"
      :sort-config="{ trigger: 'cell' }"
      ref="xTable"
      :scroll-x="{ gt: 10 }"
      :scroll-y="{ gt: 100 }"
      row-id="itemId"
      align="left"
      :checkbox-config="{
        labelField: 'name',
      }"
      :tree-config="{
        transform: true,
        rowField: 'itemId',
        parentField: 'parentId',
      }"
      :data="tableData[page]"
      @checkbox-all="selectAllEvent"
      @checkbox-change="selectChangeEvent"
    >
      <!-- 名称 -->
      <vxe-column
        field="name"
        title="名称"
        :type="category == 1 && (type == 0 || type == 3) ? 'checkbox' : ''"
        tree-node
        width="220px"
        fixed="left"
      ></vxe-column>
      <!-- 已完成/设计数量 -->
      <vxe-column
        field="completeAndPlan"
        title="已完成/设计数量"
        width="180px"
      ></vxe-column>
      <!-- 累计完成百分比（%） -->
      <vxe-column
        field="completionPercentage"
        title="累计完成百分比（%）"
        width="250px"
      >
        <template #default="{ row }">
          <div class="complete-bar">
            <div
              class="bar"
              :style="{
                width: row.completionPercentage,
              }"
            ></div>
            <div class="number">{{ row.completionPercentage }}</div>
          </div>
        </template>
      </vxe-column>
      <!-- 状态 -->
      <vxe-column field="status" title="状态" width="150px">
        <template #default="{ row }">
          <div
            class="status-tip"
            :style="{
              color: completeStatusStyle(row.status),
            }"
          >
            {{ row.status | filterCompleteStatusValue }}
          </div>
        </template>
      </vxe-column>
      <!-- 计划生产开始时间 -->
      <vxe-column field="planStartTime" title="计划生产开始时间" width="200px">
        <template #default="{ row }">
          <div v-if="!row.children || row.children.length == 0">
            <div v-if="fillMode">
              {{ row.planStartTime }}<span v-if="category == 3">周</span>
            </div>
            <planTimePicker
              allowClear
              :value.sync="row.planStartTime"
              :type="4"
              v-else
            ></planTimePicker>
          </div>
          <span v-else>{{ row.planStartTime }}</span>
        </template>
      </vxe-column>
      <!-- 计划生产结束时间 -->
      <vxe-column field="planEndTime" title="计划生产结束时间" width="200px">
        <template #default="{ row }">
          <div v-if="!row.children || row.children.length == 0">
            <div v-if="fillMode">
              {{ row.planEndTime }}<span v-if="category == 3">周</span>
            </div>
            <planTimePicker
              allowClear
              :value.sync="row.planEndTime"
              :type="4"
              v-else
            ></planTimePicker>
          </div>
          <span v-else>{{ row.planEndTime }}</span>
        </template>
      </vxe-column>
      <!-- 计划出梁开始时间 -->
      <vxe-column
        field="planJqStartTime"
        title="计划出梁开始时间"
        width="200px"
      >
        <template #default="{ row }">
          <div v-if="!row.children || row.children.length == 0">
            <div v-if="fillMode">
              {{ row.planJqStartTime }}<span v-if="category == 3">周</span>
            </div>
            <planTimePicker
              allowClear
              :value.sync="row.planJqStartTime"
              :type="4"
              v-else
            ></planTimePicker>
          </div>
          <span v-else>{{ row.planJqStartTime }}</span>
        </template>
      </vxe-column>
      <!-- 计划出梁结束时间 -->
      <vxe-column field="planJqEndTime" title="计划出梁结束时间" width="200px">
        <template #default="{ row }">
          <div v-if="!row.children || row.children.length == 0">
            <div v-if="fillMode">
              {{ row.planJqEndTime }}<span v-if="category == 3">周</span>
            </div>
            <planTimePicker
              allowClear
              :value.sync="row.planJqEndTime"
              :type="4"
              v-else
            ></planTimePicker>
          </div>
          <span v-else>{{ row.planJqEndTime }}</span>
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <vxe-pager
      background
      :current-page.sync="page"
      :page-size.sync="pageSize"
      :total="total"
      :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'FullJump']"
      @page-change="paginationChange"
    >
      <template #left>
        <div class="vxe-pager-left-tip-container">
          第<span>1</span>到<span
            >{{ Math.ceil(total / pageSize) || 1 }}页 </span
          >共<span>{{ total }}</span
          >条记录
        </div>
      </template>
    </vxe-pager>
  </div>
</template>
<script>
import { getRWList } from "@/api/wisdom-beam/planSchedule-app.js";
import { flatTreeData, getPathByKey, getNodeByHierarchy } from "@/utils";
import planTimePicker from "./planTimePicker";
export default {
  props: {
    // 1年计划  2月计划  3周计划
    category: {
      type: [String, Number],
      default: "",
    },
    //0新增 1审批  2查看  3编辑
    type: {
      type: [String, Number],
      default: "",
    },
    id: {
      type: String,
      default: "",
    },
    beamNumber: {
      type: String,
      default: "",
    },
  },
  components: {
    planTimePicker,
  },
  computed: {
    fillMode() {
      let { type } = this;
      return type == 1 || type == 2;
    },
  },
  data() {
    return {
      loading: false,
      //是否展示已编制的任务清单
      ifShowExist: 1,
      page: 1,
      pageSize: 10,
      total: 0,
      tableData: {
        1: [],
      },
      rawTreeData: {},
      checkedData: {},
    };
  },
  filters: {
    filterCompleteStatusValue(val) {
      switch (val) {
        case "1":
          return "未开工";

        case "2":
          return "进行中";

        case "3":
          return "已完工";

        default:
          break;
      }
    },
  },
  mounted() {
    this.getData();
  },
  methods: {
    //查询任务清单列表
    getData(autoType) {
      return new Promise((resolve, reject) => {
        this.loading = true;
        let { page, pageSize, ifShowExist, id, type } = this;
        getRWList({
          page,
          pageSize,
          ifShowExist: type == 3 || type == 2 ? ifShowExist : "",
          id,
          itemId: this.beamNumber,
        })
          .then((res) => {
            let { data } = res;
            let source = data?.result ?? {};
            let tableSource = source.rows ?? [];
            // 默认展开一级二级
            this.$refs.xTable.setAllTreeExpand(false);
            const rows = getNodeByHierarchy(tableSource, 2, "children");
            this.$refs.xTable.setTreeExpand(rows, true);

            this.$set(this.rawTreeData, page, tableSource);
            let flatData = flatTreeData(tableSource, "children") ?? [];
            // 自动填充先前修改填写的值
            this.autoFillValue(flatData, autoType);
            //设置表格数据
            this.$set(this.tableData, page, flatData);
            this.total = source.total || 0;

            if (!autoType) {
              this.setCheckboxRow();
            }
            resolve();
          })
          .catch((_) => {
            this.$set(this.tableData, page, []);
            this.$set(this.rawTreeData, page, []);
            this.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //监听复选框全选
    selectAllEvent(ev) {
      let { records } = ev;
      let { page } = this;
      this.$set(
        this.checkedData,
        page,
        records.map((v) => v.itemId)
      );
    },

    //监听复选框
    selectChangeEvent(ev) {
      let { records } = ev;
      let keys = records.map((v) => v.itemId);
      let { page } = this;
      this.$set(this.checkedData, page, keys);
    },

    //自动填充已经修改的值
    autoFillValue(currenData = [], autoType) {
      let { page, tableData } = this;
      let hasDataKeys = [];
      let fillKeys = [
        "planStartTime",
        "planEndTime",
        "planJqStartTime",
        "planJqEndTime",
      ];
      if (!tableData[page]) {
        return;
      }
      tableData[page].forEach((v) => {
        let { itemId } = v;
        let currentItem = currenData.find((item) => item.itemId === itemId);
        if (!currentItem) return;
        Object.keys(v).forEach((key) => {
          if (fillKeys.includes(key)) {
            currentItem[key] = v[key];
          }
        });
        if (fillKeys.some((filley) => v[filley])) {
          !hasDataKeys.includes(itemId) && hasDataKeys.push(itemId);
        }
      });
      if (!autoType) {
        this.openRowsByIds(hasDataKeys);
      }
    },

    //手动设置选中状态
    setCheckboxRow() {
      let { checkedData, page, tableData } = this;
      let checkRows = (tableData[page] ?? []).filter((v) =>
        (checkedData[page] ?? []).includes(v.itemId)
      );
      this.$refs.xTable.setCheckboxRow(checkRows, true);
    },

    //展开指定的行
    openRowsByIds(itemIds = []) {
      let { tableData, page, rawTreeData } = this;
      let itemKeys = tableData[page].filter((v) => itemIds.includes(v.itemId));
      let expandRows = itemKeys
        .map((v) => {
          return getPathByKey(
            v.itemId,
            "itemId",
            rawTreeData?.[page] ?? [],
            false,
            "children"
          );
        })
        .flat();
      this.$refs.xTable.setTreeExpand(expandRows, true);
    },

    //监听[是否展示已编制的任务清单]切换
    changeShowExist() {
      this.checkedData = {};
      this.getData(1);
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.page = currentPage;
      this.pageSize = pageSize;
      let { type } = this;
      this.getData(type == 0 || type == 3 ? "" : 1);
    },

    completeStatusStyle(val) {
      switch (val) {
        case "0":
          return "#FF993F";
        case "1":
          return "#FF3F4A";

        case "2":
          return "#0098FF";

        case "3":
          return "#4BC964";
      }
    },
  },
};
</script>
<style lang="less" scoped>
.treeTable-container {
  .ant-calendar-picker {
    width: 150px;
  }
  .radioGroup-container {
    padding: 0 0 10px 0;
  }
  .complete-bar {
    width: 128px;
    height: 10px;
    background: #ebebeb;
    border-radius: 5px;
    position: relative;
    .bar {
      position: absolute;
      height: 100%;
      background: var(--primary-color);
      top: 0;
      left: 0;
      border-radius: 5px;
      max-width: 100%;
    }
    .number {
      top: 50%;
      transform: translateY(-50%);
      left: 140px;
      position: absolute;
      white-space: nowrap;
      color: #666;
      font-size: 14px;
    }
  }
}
</style>
